/**
 * Transform script to:
 * - Replace `import { Link } from 'umi'` → `import { Link } from 'react-router-dom'` (only if used)
 * - Replace `import { history as router } from 'umi'` → `import history from '@/utils/history'`
 * - Replace `router.push()` → `history.push()`
 */
export default function transformer(file, api) {
  const j = api.jscodeshift;
  const root = j(file.source);

  let needLinkImport = false;
  let needHistoryImport = false;
  let usedHistoryAlias = null;

  // 1. 处理 umi 的 import 声明
  root.find(j.ImportDeclaration, { source: { value: 'umi' } }).forEach(path => {
    const specifiers = path.node.specifiers;

    const newSpecifiers = specifiers.filter(spec => {
      // 1a. 处理 Link
      if (spec.type === 'ImportSpecifier' && spec.imported.name === 'Link') {
        const localName = spec.local.name;

        // 检查是否被使用
        const used = root.find(j.Identifier, { name: localName }).size() > 0;
        if (used) {
          needLinkImport = true;
        }
        return false; // 删除 umi 中的 Link
      }

      // 1b. 处理 history（可能是 alias）
      if (spec.type === 'ImportSpecifier' && spec.imported.name === 'history') {
        usedHistoryAlias = spec.local.name;
        needHistoryImport = true;
        return false;
      }

      return true;
    });

    if (newSpecifiers.length === 0) {
      j(path).remove();
    } else {
      path.node.specifiers = newSpecifiers;
    }
  });

  // 2. 添加 import { Link } from 'react-router-dom'
  if (needLinkImport) {
    const alreadyHasLink = root.find(j.ImportDeclaration, {
      source: { value: 'react-router-dom' },
    }).some(p =>
      p.node.specifiers.some(
        s => s.type === 'ImportSpecifier' && s.imported.name === 'Link'
      )
    );

    if (!alreadyHasLink) {
      const importDecl = j.importDeclaration(
        [j.importSpecifier(j.identifier('Link'))],
        j.literal('react-router-dom')
      );
      root.get().node.program.body.unshift(importDecl);
    }
  }

  // 3. 替换 router.xxx → history.xxx
  if (needHistoryImport && usedHistoryAlias) {
    // 替换所有 router.xxx → history.xxx
    root.find(j.Identifier, { name: usedHistoryAlias }).forEach(path => {
      if (
        path.parent.value.type === 'MemberExpression' &&
        path.parent.value.object === path.value
      ) {
        path.replace(j.identifier('history'));
      }
    });

    // 插入 import history from '@/utils/history'
    const alreadyHasHistory = root.find(j.ImportDeclaration, {
      source: { value: '@/utils/history' },
    }).size() > 0;

    if (!alreadyHasHistory) {
      const importDecl = j.importDeclaration(
        [j.importDefaultSpecifier(j.identifier('history'))],
        j.literal('@/utils/history')
      );
      root.get().node.program.body.unshift(importDecl);
    }
  }

  return root.toSource({ quote: 'single' });
}
// jscodeshift -t ./test/umi-react.js /Users/xiaodian/Desktop/earth/src/components/SearchBlock/index.tsx
// jscodeshift -t ./test/umi-react.js /Users/xiaodian/Desktop/earth/src/**/*.tsx